const add = async (model, body, res) => {
	await model.create(body);
	res.json({
		code: 0,
		data: null,
		msg: 'success'
	});
};
const page = async (model, body, res, arr) => {
	let currentPage = parseInt(body.currentPage);
	let pageSize = parseInt(body.pageSize);
	let where = {};
	for (let i in body) {
		arr.forEach(item => {
			if (body[i] !== '' && i === item) {
				where[i] = body[i];
			}
		});
	}
	await model
		.findAndCountAll({
			where: where,
			offset: (currentPage - 1) * pageSize,
			limit: pageSize
		})
		.then(result => {
			res.json({
				code: 0,
				data: {
					currPage: parseInt(body.currentPage),
					list: result.rows,
					pageSize: parseInt(body.pageSize),
					totalCount: result.count,
					totalPage: Math.ceil(result.count / parseInt(body.pageSize))
				},
				msg: 'success'
			});
		});
};
const list = async (model, body, res) => {
	await model
		.findAll()
		.then(result => {
			res.json({
				code: 0,
				data: result,
				msg: 'success'
			});
		})
		.catch(err => {
			res.json({
				code: 500,
				data: null,
				msg: err
			});
		});
};
const info = async (model, body, res) => {
	await model
		.findOne({
			where: { id: body.id },
			raw: true
		})
		.then(result => {
			res.json({
				code: 0,
				data: result,
				msg: 'success'
			});
		})
		.catch(err => {
			res.json({
				code: 500,
				data: null,
				msg: err
			});
		});
};
const update = async (model, body, res) => {
	body.updated_time = Date.parse(new Date()) / 1000;
	delete body.password;
	await model
		.update(body, {
			where: { id: body.id }
		})
		.then(result => {
			res.json({
				code: 0,
				data: null,
				msg: 'success'
			});
		})
		.catch(err => {
			res.json({
				code: 500,
				data: null,
				msg: err
			});
		});
};
const del = async (model, body, res) => {
	await model
		.destroy({
			where: { id: body.id }
		})
		.then(result => {
			res.json({
				code: 0,
				data: null,
				msg: 'success'
			});
		})
		.catch(err => {
			res.json({
				code: 500,
				data: null,
				msg: err
			});
		});
};
module.exports = {
	add,
	page,
	list,
	info,
	update,
	del
};
